package com.ihighest.app.infox.adapter;

import org.json.JSONArray;
import org.json.JSONException;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.infox.R;

public class ProductAdapter extends BaseAdapter {

	private final LayoutInflater inflater;
	Context context;
	JSONArray array;

	public ProductAdapter(Context context, JSONArray array) {
		super();
		this.context = context;
		this.array = array;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		if (array == null) {
			return 0;
		}

		return array.length();
	}

	@Override
	public Object getItem(int arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return arg0;
	}

	@Override
	public View getView(int arg0, View convertView, ViewGroup arg2) {
		// TODO Auto-generated method stub

		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = inflater.inflate(R.layout.infox_product_item, null);

			holder.title = (TextView) convertView.findViewById(R.id.id_title);
			holder.describ = (TextView) convertView.findViewById(R.id.id_describ);
			holder.image = (ImageView) convertView.findViewById(R.id.id_image);

			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		try {
			holder.title.setText(array.getJSONObject(arg0).getString("title"));
			// holder.describ.setText(array.getJSONObject(arg0).getString(""));
			String imageurl = array.getJSONObject(arg0).getString("image");

			// DisplayImageOptions defaultOptions = new
			// DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.infox_img_loadrong)
			// .showImageOnFail(R.drawable.infox_img_loadrong).showImageOnLoading(R.drawable.infox_img_loadrong).cacheInMemory(true)
			// .cacheOnDisc(true).build();
			// ImageLoader.getInstance().displayImage(imageurl, holder.image,
			// defaultOptions);
			AppKit.SetNormalImg(imageurl, holder.image);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return convertView;
	}

	class ViewHolder {

		ImageView image;
		TextView title;
		TextView describ;

	}

	/**
	 * 替换当前数据源数据
	 * 
	 * @param moreArry
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:23
	 */
	public void setData(JSONArray jsonArray) {
		this.array = jsonArray;
		notifyDataSetChanged();
	}

	/**
	 * 向已有数据源中追加数据
	 * 
	 * @param jsonArray
	 * 
	 * @author lkx Created at 2015-10-20 下午8:49:00
	 */
	public void appendData(JSONArray jsonArra) {
		try {
			array = AppKit.joinJSONArray(array, jsonArra);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		notifyDataSetChanged();
	}

}
